package view;

import controller.AddSequenceListener;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import model.Instrument;
import util.Images;
import util.NoSelectionButtonGroup;

/**
 * A list of instrument buttons. The size and layout of this component corresponds
 * to the size and layout of TrackListPanel as they match the sequence they
 * represent.
 */
public class InstrumentListPanel extends ScrollableListPanel {

	private JButton addButton;
	private Box emptySpace;
	private ButtonGroup buttonGroup;

	public InstrumentListPanel() {
		this.setLayout(new GridLayout(0, 1, 0, 1));
		this.setOpaque(false);

		buttonGroup = new NoSelectionButtonGroup();

		addButton = new JButton("+");
		addButton.setMargin(new Insets(0,0,0,0));
		addButton.setPreferredSize(new Dimension(32,31));

		this.emptySpace = Box.createHorizontalBox();

		this.add(addButton);
		this.add(emptySpace);
	}

	public void changeInstrumentIcon(int instrumentIndex, Instrument newInstrument) {
		((InstrumentButton)this.getComponent(instrumentIndex)).setIcon(
			new ImageIcon(Images.getInstrumentIcon(newInstrument))
		);
	}

	public void removeInstrumentButton(int instrumentIndex) {
		buttonGroup.remove((InstrumentButton)this.getComponent(instrumentIndex));
		this.remove(instrumentIndex);
		//Prevent the 2 non-instrument components from being removed.
		int end = this.getComponentCount()-2;
		for(int i = instrumentIndex; i < end; i++) {
			//Adjust alternating colours.
			this.getComponent(i).setBackground(new Color(0xFEFEFE-0x222222*(i%2)));
		}
	}

	public void addInstrumentButton(InstrumentButton instrumentButton) {
		//Remove these temporarily to make space for the instrument button
		this.remove(emptySpace);
		this.remove(addButton);

		int i = this.getComponentCount();
		instrumentButton.setBackground(new Color(0xFEFEFE-0x222222*(i%2)));
		buttonGroup.add(instrumentButton);
		this.add(instrumentButton);

		//Add them back to the end.
		this.add(addButton);
		this.add(emptySpace);
	}

	public void setAddSequenceListener(AddSequenceListener asl) {
		//Remove existing listeners to prevent conflicts.
		for(ActionListener al : addButton.getActionListeners()) {
			addButton.removeActionListener(al);
		}
		addButton.addActionListener(asl);
	}

	@Override
	public Dimension getPreferredScrollableViewportSize() {
		return new Dimension(TrackPanel.DEFAULT_HEIGHT, EditorPanel.MIN_HEIGHT);
	}
}
